package org.lee.nio.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author jackielee
 * @version 1.0
 * @description NIOClient
 * @date 2021/3/8
 **/
public class NIOClient {
    // 通道管理
    private Selector selector;

    /**
     * 初始化
     * @param ip
     * @param port
     */
    public void initClient(String ip, int port) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false); // 非阻塞
        selector = Selector.open();
        // 客户端连接服务器，方法执行并没有实现连接，需要listen()方法中调用channel.finishConnect()才能完成连接
        channel.connect(new InetSocketAddress(ip, port));
        // 将通道管理器与通道绑定，并注册SelectionKey.OP_CONNECT事件
        channel.register(selector, SelectionKey.OP_CONNECT);
    }

    // 轮询方式监听selector上是否需要处理事件
    public void listen() throws IOException {
        while (true){
            selector.select();
            Iterator ite = selector.selectedKeys().iterator();
            while (ite.hasNext()){
                SelectionKey key = (SelectionKey)ite.next();
                ite.remove();
                if(key.isConnectable()){ // 连接
                    SocketChannel channel = (SocketChannel)key.channel();
                    if(channel.isConnectionPending()){ // 正在连接
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false); // 非阻塞
                    System.out.println("连接服务器成功，say hello to server.");
                    channel.write(ByteBuffer.wrap("hello server,I'm from the nio client.".getBytes()));
                    channel.register(selector, SelectionKey.OP_READ); // 连接成功后，可接受服务端信息，需要设置读权限
                }else if(key.isReadable()){
                    read(key);
                }
            }
        }
    }

    private void read(SelectionKey key) throws IOException {
        SocketChannel channel = (SocketChannel)key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        channel.read(buffer);
        byte[] data = buffer.array();
        String msg = new String(data).trim();
        System.out.println("收到:" + msg);
    }

    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClient("127.0.0.1", 8080);
        client.listen();
    }
}
